package com.mosaic.girih;

import java.io.File;
import java.io.FileOutputStream;
import java.util.StringTokenizer;

import com.example.girih.R;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.Toast;

public class DisplayActivity extends MainActivity {
	private ImageView mIV;
	private Bitmap mBitmap;

	String picturePath;
	String outFolder = "output";
	String outFile = "default_output";
	boolean enableSaveAndRestore = false;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		mIV = new ImageView(this);
		setContentView(mIV);
		setContentView(R.layout.activity_display);

		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

		// Get the intent
		Intent intent = getIntent();

		// Retrieve picture path
		picturePath = intent.getStringExtra("picturePath");
		StringTokenizer tokens = new StringTokenizer(picturePath, "/");
		String str = outFile;
		while (tokens.hasMoreTokens())
			str = tokens.nextToken();
		outFile = str;

		mIV = (ImageView) findViewById(R.id.iv_img);
		// Check image dimension to avoid out of memory issue
		BitmapFactory.Options options = new BitmapFactory.Options();
		// Load image bitmap parameters
		options.inJustDecodeBounds = true;
		mBitmap = BitmapFactory.decodeFile(picturePath, options);
		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, 512, 512);
		// Load image bitmap data
		options.inJustDecodeBounds = false;
		mBitmap = BitmapFactory.decodeFile(picturePath, options);

		mIV.setImageBitmap(mBitmap);
		mIV.invalidate();

		// Display a short message on screen
		Toast.makeText(DisplayActivity.this,
				"Touch the screen to apply the mosaic filter",
				Toast.LENGTH_LONG).show();
	}

	// From Google: Return sample ratio to resize image
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			// Calculate ratios of height and width to requested height and
			// width
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			// Choose the smallest ratio as inSampleSize value, this will
			// guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}

		return inSampleSize;
	}

	// Save the result onto a file on SD card
	private void saveThePicture(String dirname, String filename) {
		// Make sure the folder is available
		File sddir = new File(dirname);
		if (!sddir.mkdirs()) {
			if (sddir.exists()) {
			} else {
				Toast.makeText(DisplayActivity.this, "Folder error",
						Toast.LENGTH_SHORT).show();
				return;
			}
		}

		// Save the image
		try {
			String outname = dirname + filename;
			FileOutputStream fos = new FileOutputStream(outname);
			mBitmap.compress(CompressFormat.JPEG, 75, fos);

			fos.flush();
			fos.close();
			// Display a short message on screen
			Toast.makeText(DisplayActivity.this,
					"Mosaic was saved as " + outname, Toast.LENGTH_SHORT)
					.show();
		} catch (Exception e) {
			Log.e("mosaic.log", e.toString());
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_UP:
			// Perform the mosaic operation
			long start = SystemClock.elapsedRealtime();

			mBitmap = mFilters[settings.getInt(filterIdxKey, 0)]
					.applyMosaic(mBitmap);

			// Put the updated bitmap into the main view
			mIV.setImageBitmap(mBitmap);
			mIV.invalidate();

			long end = SystemClock.elapsedRealtime();

			// Display a short message on screen
			Toast.makeText(DisplayActivity.this,
					"Picture was processed in " + (end - start) + " ms.",
					Toast.LENGTH_SHORT).show();

			// Change menu
			enableSaveAndRestore = true;
			if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
				// only for 3.0 and newer versions
				invalidateOptionsMenu();
			}
			return (true);

		case MotionEvent.ACTION_DOWN:
			break;
		}

		return super.onTouchEvent(event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_display, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// Change menu items to enable save and restore
		MenuItem save = menu.findItem(R.id.menu_save);
		MenuItem restore = menu.findItem(R.id.menu_restore);
		if (enableSaveAndRestore) {
			save.setEnabled(true);
			restore.setEnabled(true);
		} else {
			save.setEnabled(false);
			restore.setEnabled(false);
		}
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Manages user selection in the menu
		super.onOptionsItemSelected(item);

		int menuId = item.getItemId();
		switch (menuId) {
		case R.id.menu_settings:
			// Launch SettingsActivity
			Intent i = new Intent(this, SettingsActivity.class);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
			break;
		case R.id.menu_restore:
			// Check image dimension to avoid out of memory issue
			BitmapFactory.Options options = new BitmapFactory.Options();
			// Load image bitmap parameters
			options.inJustDecodeBounds = true;
			mBitmap = BitmapFactory.decodeFile(picturePath, options);
			// Calculate inSampleSize
			options.inSampleSize = calculateInSampleSize(options, 512, 512);
			// Restore image bitmap data
			options.inJustDecodeBounds = false;
			mBitmap = BitmapFactory.decodeFile(picturePath, options);
			
			enableSaveAndRestore = false;
			mIV.setImageBitmap(mBitmap);
			mIV.invalidate();
			break;
		case R.id.menu_save:
			// Save picture
			saveThePicture(Environment.getExternalStorageDirectory() + "/mosaic/"
					+ outFolder + "/", outFile + ".jpg" );
			break;
		}

		return true;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// When the user center presses back
			finish();
			return true;
		}
		return false;
	}
}
